<template>
  <div class="tool-page">
    <div class="tool-header">
      <h1>Logo转ICO工具</h1>
      <p>将Logo图片转换为ICO格式，支持多种尺寸和颜色深度</p>
    </div>
    
    <div class="logo-to-ico">
      <!-- 上传区域 -->
      <div class="upload-section">
        <div class="upload-area" @click="triggerFileInput" @dragover.prevent @drop="handleFileDrop">
          <input 
            type="file" 
            ref="fileInput" 
            @change="handleFileSelect" 
            accept="image/*" 
            class="file-input" 
          />
          <div class="upload-content">
            <i class="fa fa-file-image-o upload-icon"></i>
            <h3>点击或拖拽Logo图片到这里</h3>
            <p>支持PNG、JPG、SVG等格式</p>
          </div>
        </div>
        
        <div v-if="fileName" class="file-info">
          <p><strong>已选择文件:</strong> {{ fileName }}</p>
          <p><strong>文件大小:</strong> {{ fileSize }}</p>
          <button @click="clearFile" class="clear-btn">清除文件</button>
        </div>
      </div>

      <!-- 转换设置 -->
      <div v-if="imageData" class="settings-section">
        <h3>ICO转换设置</h3>
        
        <div class="preview-section">
          <div class="preview-container">
            <img :src="imageData" alt="Logo预览" class="logo-preview" />
          </div>
          <div class="preview-info">
            <p><strong>原始尺寸:</strong> {{ originalWidth }} × {{ originalHeight }} 像素</p>
            <p><strong>文件格式:</strong> {{ fileType }}</p>
          </div>
        </div>

        <div class="settings-grid">
          <div class="setting-group">
            <label class="setting-label">ICO尺寸设置：</label>
            <div class="size-options">
              <label v-for="size in sizeOptions" :key="size" class="size-option">
                <input 
                  type="checkbox" 
                  :value="size" 
                  v-model="selectedSizes" 
                  class="size-checkbox"
                />
                <span class="size-label">{{ size }}×{{ size }}</span>
              </label>
            </div>
          </div>

          <div class="setting-group">
            <label class="setting-label">颜色深度：</label>
            <select v-model="colorDepth" class="setting-select">
              <option value="32">32位真彩色（带Alpha通道）</option>
              <option value="24">24位真彩色</option>
              <option value="8">256色</option>
              <option value="4">16色</option>
              <option value="1">单色（黑白）</option>
            </select>
          </div>

          <div class="setting-group">
            <label class="setting-label">
              <input type="checkbox" v-model="preserveAspectRatio" />
              保持宽高比
            </label>
          </div>

          <div class="setting-group">
            <label class="setting-label">背景处理：</label>
            <select v-model="backgroundType" class="setting-select">
              <option value="transparent">透明背景</option>
              <option value="white">白色背景</option>
              <option value="black">黑色背景</option>
              <option value="custom">自定义颜色</option>
            </select>
            <input 
              v-if="backgroundType === 'custom'" 
              type="color" 
              v-model="customBackground" 
              class="color-picker"
            />
          </div>
        </div>

        <!-- 转换按钮 -->
        <div class="action-section">
          <button @click="convertToIco" class="convert-btn" :disabled="selectedSizes.length === 0">
            <i class="fa fa-refresh"></i>
            转换为ICO
          </button>
        </div>
      </div>

      <!-- 转换结果 -->
      <div v-if="icoData" class="result-section">
        <h3>转换结果</h3>
        
        <div class="result-info">
          <p><strong>ICO文件大小:</strong> {{ formatFileSize(icoData.size) }}</p>
          <p><strong>包含尺寸:</strong> {{ selectedSizes.join('×') }} 像素</p>
          <p><strong>颜色深度:</strong> {{ colorDepth }}位</p>
        </div>

        <div class="preview-grid">
          <div v-for="size in selectedSizes" :key="size" class="ico-preview">
            <div class="preview-box">
              <span class="preview-size">{{ size }}×{{ size }}</span>
            </div>
          </div>
        </div>

        <div class="download-section">
          <button @click="downloadIco" class="download-btn">
            <i class="fa fa-download"></i>
            下载ICO文件
          </button>
          
          <div class="file-name-input">
            <label>文件名：</label>
            <input 
              type="text" 
              v-model="outputFileName" 
              placeholder="输入ICO文件名" 
              class="name-input"
            />
            <span class="file-extension">.ico</span>
          </div>
        </div>
      </div>

      <!-- 使用说明 -->
      <div class="instructions-section">
        <h3>使用说明</h3>
        <div class="instructions">
          <p><strong>1. 上传Logo图片</strong> - 支持PNG、JPG、SVG等常见格式</p>
          <p><strong>2. 设置转换参数</strong> - 选择ICO尺寸、颜色深度等选项</p>
          <p><strong>3. 转换为ICO</strong> - 点击转换按钮生成ICO文件</p>
          <p><strong>4. 下载使用</strong> - 下载生成的ICO文件用于网站或应用程序</p>
          
          <div class="tips">
            <h4>最佳实践：</h4>
            <ul>
              <li>推荐包含16×16、32×32、48×48等常用尺寸</li>
              <li>PNG格式的透明Logo转换效果最佳</li>
              <li>32位颜色深度支持Alpha透明通道</li>
              <li>正方形Logo的转换效果最好</li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        <i class="fa fa-exclamation-triangle"></i>
        {{ error }}
      </div>
    </div>
  </div>
</template>

<script>
// 导入图像处理库（这里使用Canvas API进行图像处理）

export default {
  name: 'LogoToIco',
  data() {
    return {
      fileName: '',
      fileSize: '',
      fileType: '',
      imageData: null,
      originalWidth: 0,
      originalHeight: 0,
      
      // ICO设置
      sizeOptions: [16, 24, 32, 48, 64, 128, 256],
      selectedSizes: [16, 32, 48],
      colorDepth: '32',
      preserveAspectRatio: true,
      backgroundType: 'transparent',
      customBackground: '#ffffff',
      
      // 转换结果
      icoData: null,
      outputFileName: 'logo',
      
      error: ''
    }
  },
  methods: {
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    
    handleFileSelect(event) {
      const file = event.target.files[0];
      if (file) {
        this.processFile(file);
      }
    },
    
    handleFileDrop(event) {
      event.preventDefault();
      const file = event.dataTransfer.files[0];
      if (file) {
        this.processFile(file);
      }
    },
    
    processFile(file) {
      if (!file.type.startsWith('image/')) {
        this.error = '请选择图片文件';
        return;
      }
      
      this.fileName = file.name;
      this.fileSize = this.formatFileSize(file.size);
      this.fileType = file.type.split('/')[1].toUpperCase();
      
      const reader = new FileReader();
      reader.onload = (e) => {
        this.imageData = e.target.result;
        
        // 获取图片尺寸
        const img = new Image();
        img.onload = () => {
          this.originalWidth = img.width;
          this.originalHeight = img.height;
          
          // 自动设置输出文件名
          const baseName = file.name.replace(/\.[^/.]+$/, '');
          this.outputFileName = baseName;
        };
        img.src = this.imageData;
      };
      reader.readAsDataURL(file);
      
      this.error = '';
    },
    
    clearFile() {
      this.fileName = '';
      this.fileSize = '';
      this.fileType = '';
      this.imageData = null;
      this.originalWidth = 0;
      this.originalHeight = 0;
      this.icoData = null;
      this.$refs.fileInput.value = '';
    },
    
    async convertToIco() {
      if (!this.imageData || this.selectedSizes.length === 0) {
        this.error = '请先选择图片和尺寸';
        return;
      }
      
      try {
        this.error = '';
        
        // 创建Canvas处理图像
        const img = new Image();
        img.src = this.imageData;
        
        await new Promise((resolve) => {
          img.onload = resolve;
        });
        
        // 创建ICO文件数据（这里简化处理，实际需要生成真正的ICO格式）
        const icoBlob = await this.generateIcoBlob(img);
        
        this.icoData = {
          blob: icoBlob,
          size: icoBlob.size
        };
        
      } catch (err) {
        this.error = '转换失败: ' + err.message;
      }
    },
    
    async generateIcoBlob(originalImage) {
      // 这里简化处理，实际需要生成真正的ICO格式
      // 实际项目中可以使用专门的ICO生成库
      
      // 创建一个Canvas来生成预览图像
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      // 使用第一个选中的尺寸作为预览
      const size = Math.max(...this.selectedSizes);
      canvas.width = size;
      canvas.height = size;
      
      // 设置背景
      if (this.backgroundType !== 'transparent') {
        let bgColor = '#ffffff';
        if (this.backgroundType === 'black') bgColor = '#000000';
        else if (this.backgroundType === 'custom') bgColor = this.customBackground;
        
        ctx.fillStyle = bgColor;
        ctx.fillRect(0, 0, size, size);
      }
      
      // 绘制图像（保持宽高比）
      const scale = Math.min(size / originalImage.width, size / originalImage.height);
      const scaledWidth = originalImage.width * scale;
      const scaledHeight = originalImage.height * scale;
      const x = (size - scaledWidth) / 2;
      const y = (size - scaledHeight) / 2;
      
      ctx.drawImage(originalImage, x, y, scaledWidth, scaledHeight);
      
      // 将Canvas转换为Blob（模拟ICO格式）
      return new Promise((resolve) => {
        canvas.toBlob((blob) => {
          resolve(blob);
        }, 'image/png');
      });
    },
    
    downloadIco() {
      if (!this.icoData) return;
      
      const fileName = this.outputFileName.trim() || 'logo';
      const fullFileName = fileName.endsWith('.ico') ? fileName : fileName + '.ico';
      
      // 创建下载链接
      const url = URL.createObjectURL(this.icoData.blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = fullFileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    },
    
    formatFileSize(bytes) {
      if (bytes < 1024) {
        return bytes + ' B';
      } else if (bytes < 1024 * 1024) {
        return (bytes / 1024).toFixed(2) + ' KB';
      } else {
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
      }
    }
  },
  
  watch: {
    backgroundType(newVal) {
      if (newVal !== 'custom') {
        this.customBackground = '#ffffff';
      }
    }
  }
}
</script>

<style scoped>
.logo-to-ico {
  max-width: 800px;
  margin: 0 auto;
}

.upload-section {
  margin-bottom: 2rem;
}

.upload-area {
  border: 2px dashed var(--border-color);
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: var(--primary-color);
  background-color: rgba(52, 152, 219, 0.05);
}

.file-input {
  display: none;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.upload-icon {
  font-size: 3rem;
  color: var(--primary-color);
}

.upload-content h3 {
  margin: 0;
  color: var(--secondary-color);
}

.upload-content p {
  margin: 0;
  color: var(--text-light);
}

.file-info {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.file-info p {
  margin: 0.5rem 0;
}

.clear-btn {
  background-color: var(--accent-color);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 0.5rem;
}

.settings-section {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
}

.settings-section h3 {
  margin-bottom: 1rem;
  color: var(--secondary-color);
}

.preview-section {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
  align-items: center;
}

.preview-container {
  width: 100px;
  height: 100px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-preview {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.preview-info p {
  margin: 0.5rem 0;
  font-size: 0.9rem;
}

.settings-grid {
  display: grid;
  gap: 1.5rem;
}

.setting-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.setting-label {
  font-weight: 500;
  color: var(--secondary-color);
}

.size-options {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.size-option {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.size-option:hover {
  border-color: var(--primary-color);
}

.size-checkbox:checked + .size-label {
  color: var(--primary-color);
  font-weight: 500;
}

.setting-select {
  padding: 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: white;
}

.color-picker {
  width: 50px;
  height: 30px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  cursor: pointer;
}

.action-section {
  margin-top: 1.5rem;
}

.convert-btn {
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: background-color 0.2s;
}

.convert-btn:hover:not(:disabled) {
  background-color: #2980b9;
}

.convert-btn:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.result-section {
  background-color: #e8f5e8;
  border: 1px solid #c8e6c9;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
}

.result-section h3 {
  margin-bottom: 1rem;
  color: #2e7d32;
}

.result-info p {
  margin: 0.5rem 0;
  font-size: 0.9rem;
}

.preview-grid {
  display: flex;
  gap: 1rem;
  margin: 1rem 0;
  flex-wrap: wrap;
}

.ico-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.preview-box {
  width: 60px;
  height: 60px;
  border: 1px solid #c8e6c9;
  border-radius: 4px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-size {
  font-size: 0.8rem;
  color: #2e7d32;
  font-weight: 500;
}

.download-section {
  display: flex;
  gap: 1rem;
  align-items: center;
  flex-wrap: wrap;
}

.download-btn {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
}

.download-btn:hover {
  background-color: #218838;
}

.file-name-input {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.name-input {
  padding: 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  min-width: 150px;
}

.file-extension {
  color: var(--text-light);
  font-size: 0.9rem;
}

.instructions-section {
  background-color: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  padding: 1.5rem;
}

.instructions-section h3 {
  margin-bottom: 1rem;
  color: #856404;
}

.instructions p {
  margin: 0.5rem 0;
  line-height: 1.5;
}

.tips {
  margin-top: 1rem;
  padding: 1rem;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 6px;
}

.tips h4 {
  margin-bottom: 0.5rem;
  color: #856404;
}

.tips ul {
  margin: 0;
  padding-left: 1.5rem;
}

.tips li {
  margin: 0.25rem 0;
  line-height: 1.4;
}

.error-message {
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  color: #721c24;
  padding: 1rem;
  border-radius: 6px;
  margin-top: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

@media (max-width: 768px) {
  .preview-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .download-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .file-name-input {
    width: 100%;
  }
  
  .name-input {
    flex: 1;
  }
}
</style>